<template>
  <div style="background-color: #f6f6f6" >
    <el-row>
      <el-col :offset="2" :span="20">
        <div class="dw-table-form" style="padding-left: 20px;">
          <el-form :inline="true" :model="question" class="dw-form-inline" size="medium">
            <el-form-item label="搜索">
              <el-input v-model="formInline.questionName" clearable="clearable"
                        placeholder="请输入要查询的题目"></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px;">
              <el-button type="primary" @click="queryList">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="dw-table">
          <div class="dw-table-title">
            <el-row :span="24" align="middle" justify="space-between" type="flex">
              <el-col :span="4"><h3>题库管理</h3></el-col>

              <el-col :span="20" style="text-align: right;">
                <el-dropdown @command="handleAdd">
                  <el-button plain type="primary">添加问题<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="0">单独添加</el-dropdown-item>
                    <el-dropdown-item command="1">批量导入</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>

              </el-col>

            </el-row>
          </div>

          <el-table :data="questionData.slice((currentPage-1)*pageSize,currentPage*pageSize)" border="border" stripe
                    style="width: 100%">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="160" type="index" label="问题序号"></el-table-column>
<!--            <el-table-column label="问题编号" prop="questionNum" width="160"></el-table-column>-->
            <el-table-column label="题干信息" prop="content" width="600"></el-table-column>
            <el-table-column label="问题类型" prop="type" style="speak-time: initial" width="160" >
              <template v-slot="scope">
                {{ formatType(scope.row.type) }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-tooltip content="查看问题详情" effect="dark" placement="top">
                  <el-button circle content="查看" class="el-icon-aim" size="medium" type="primary"
                             @click="openQuestion(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <div class="dw-pagination">
            <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              :page-sizes="[5,10,20,50]"
              :total="total"
              background
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
<!--    ！！！查看问题详情-->

    <div >

      <el-dialog title="问题详情" :visible.sync="checkDialogFormVisible" style="padding-top: 100px;margin-left:250px;width:900px;padding-right: 900px" append-to-body width="80%" height="60%" center>
        <el-form ref="addQuestionData" :model="questionForm" label-width="auto" class="addSupplierListForm">
          <el-form-item label="题干信息" prop="content" style="padding-bottom: 20px;" >
            <div style="font-weight: bold">
              {{questionForm.content}}
            </div>
          </el-form-item>

          <el-form-item label="题目类型" prop="formatType(type)" style="padding-bottom: 20px;">
            <template v-slot="scope" >
              <div style="font-weight: bold">
                {{ formatType(questionForm.type) }}
              </div>
            </template>
<!--            {{}}-->
<!--            <el-input v-model="questionForm.type" disabled></el-input>-->
          </el-form-item>

<!--          <el-form-item v-for="(optionContent, index) in questionForm.optionContents" :label="'选项' + (index + 1)" style="padding-bottom: 20px">-->
<!--            <el-input v-model="optionContent" width="60%" disabled></el-input>-->
<!--          </el-form-item>-->

          <el-form-item
            v-for="(optionContent, index) in questionForm.optionContents"
            :label="'选项' + (index + 1)"
            :key="index"
            style="padding-bottom: 20px"
          >
            <div style="font-weight: bold">
              {{optionContent}}
            </div>
          </el-form-item>

        </el-form>
      </el-dialog>

    </div>

<!--    ！！！创建问题-->

    <div >

      <el-dialog :title="dialogTitle" :visible.sync="addDialogFormVisible" style="padding-top: 100px;margin-left:250px;width:900px;padding-right: 900px" append-to-body width="80%" height="60%" center>
        <el-form ref="addQuestionData" :rules="addQuestionDataRules" :model="questionForm" label-width="auto" class="addSupplierListForm">
          <el-form-item label="题干信息" prop="content" style="padding-bottom: 20px">
            <el-input v-model="questionForm.content"></el-input>
          </el-form-item>

          <el-form-item label="题目类型" prop="type" style="padding-bottom: 20px">
            <el-select v-model="questionForm.type" placeholder="请选择题目类型">
              <el-option label="单选" value="0"></el-option>
              <el-option label="多选" value="2"></el-option>
              <el-option label="文本" value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            v-if="questionForm.type != 1"
            v-for="(optionContent, index) in questionForm.optionContents"
            :label="'选项' + (index + 1)"
            :key="optionContent.key"
            :prop="'optionContents.' + index + '.content'"
            :rules="addQuestionDataRules" style="padding-bottom: 20px"
          >
            <el-input v-model="optionContent.content" width="60%"></el-input><el-button @click.prevent="removeOptionContent(optionContent)">删除</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('addQuestionData')" style="margin-right: 120px">提交</el-button>
            <el-button @click="addOptionContent" style="margin-right: 120px">新增选项</el-button>
            <el-button @click="resetForm('addQuestionData')">重置</el-button>
          </el-form-item>

        </el-form>
      </el-dialog>

    </div>

    <div>
      <el-dialog title="批量导入问题" :visible.sync="importDialogFormVisible"
                 style="padding-top: 200px;margin-left:500px;width:900px" append-to-body>
        <el-form :model="question" label-position="left">
          <el-form-item style="padding-bottom: 20px;padding-left: 25px;padding-right: 100px">
            <el-upload drag limit="1" :auto-upload="false" :action="uploadUrl"
                       :before-upload="beforeUpload" :on-change="fileChange" :on-exceed="exceedFile"
                       accept=".xlsx,.xls" :file-list="fileList">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">请按模板上传Excel文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item style="padding-bottom: 20px;padding-left: 150px">
            <el-button type="primary" icon="el-icon-download" @click="getModelExcel()">下载模板</el-button>
            <el-button type="success" icon="el-icon-upload" @click="upload()">确认上传</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

  </div>
</template>


<script>

import {
  queryQuestionList,
  addQuestion,
  uploadQuestionData,
} from "../../api/user/user-question";

export default {
  name: "QuestionList",
  data() {
    return {
      timer: null,
      count: 0,
      currentUserId: '',
      currentUserName: 'devUser',
      question: {
        must: 0,
        questionNum: '',
        content: '',
        id: '',
        type: 0,
        optionContent:[

        ]
      },
      questionData: [],

      questionForm: {
        id: null,
        content: '',
        type: '',
        optionContents: [
          {content:''}
        ]
      },

      addQuestionDataRules: {
        content: [
          {required: true, message: '请输入问题题干', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'},
          {type: 'string', message: '请输入正确的问题题干', trigger: ['blur', 'change']}
        ],
        questionType: [
          {required: true, message: '请输入题型', trigger: 'blur'},
          {min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur'},
          {type: 'string', message: '请输入正确的题型', trigger: ['blur', 'change']}
        ],
        optionContents: [
          {required: true, message: '请输入选项信息', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'},
          {type: 'string', message: '请输入正确的选项信息', trigger: ['blur', 'change']}
        ]
      },

      pageSize: 10,
      currentPage: 1,
      total: 0,

      fileList: [],

      formInline: {
        questionName: ''
      },
      dialogTitle: '创建题目',
      addDialogFormVisible: false,
      importDialogFormVisible: false,
      checkDialogFormVisible: false,
      formLabelWidth: '120px'
    }
  },
  created() {
    this.queryList()
  },
  methods: {

    getModelExcel(){
      window.location.href="http://172.18.28.123:8050/question/getModelExcel";
    },
    cleanQuestionFromBuffer(){
      this.questionForm.type = ''
      this.questionForm.content = ''
      this.questionForm.id = null
      this.questionForm.optionContents = []
    },

    formatType(type){
      const map = {
        0 : '单选题',
        1 : '文本题',
        2 : '多选题'
      }
      return map[type]
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
    },
    queryList() {
      const questionName = this.formInline.questionName
      console.log("groupName->>>>" + questionName);
      queryQuestionList(questionName).then((res) => {
        // console.log("res----->")
        // console.log(res);
        // console.log(res.data.data)
        this.questionData = res.data.data
        this.total = this.questionData.length
        // console.log(this.questionData)
        // console.log(this.total);
      })
      this.total = this.questionData.length
    },
    openQuestion(question) {
      // console.log(question)
      this.dialogTitle = '查看问题详情'
      this.questionForm.content = question.content
      this.questionForm.type = question.type
      this.questionForm.optionContents = eval('('+question.optionContent+')');
      // this.questionForm.optionContents = question.optionContent
      this.checkDialogFormVisible = true;
      console.log(this.questionForm)
    },
    handleAdd(command) {
      this.cleanQuestionBuffer()
      if (command == '0') {
        //单独添加问题
        this.dialogTitle = '单独创建问题'
        this.addDialogFormVisible = true
      }
      if (command == '1') {
        //批量导入问题
        this.dialogTitle = '批量导入问题'
        this.importDialogFormVisible = true
      }
    },
    delayFlush() {
      clearTimeout(this.timer); //清除延迟执行
      this.timer = setTimeout(() => {  //设置延迟执行
        this.queryList(this.formInline.questionName)
      }, 1000)
    },


    upload() {
      if (this.fileList.length === 0) {
        this.$message.warning("请上传文件");
      } else {
        // this.$message(this.fileList[0].name)
        let form = new FormData()
        form.append("file",this.fileList[0])
        uploadQuestionData(form).then((response)=>{
          // console.log(response)
          const httpResult = response.data
          if (httpResult.code === 200) {
            this.$message.success('批量导入成功，即将刷新数据')
            this.importDialogFormVisible = false
            this.queryList()
          } else {
            this.$message.error(httpResult.message)
          }
        })
      }
    },

    uploadUrl: function (){
      return ''
    },

    beforeUpload(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (extension !== "xls"&&extension !== "xlsx") {
        this.$message.warning("只能上传后缀是.xls或.xlsx的文件");
      }
    },

    fileChange(file) {
      if(this.fileList.length===0){
        this.fileList.push(file.raw);
      }
      console.log("fileList.length:"+this.fileList.length)
    },

    exceedFile(files, fileList) {
      this.$message.warning(
        `只能选择1个文件，当前共选择了 ${
          files.length + fileList.length
        } 个`
      );
    },
    cleanQuestionBuffer() {
      this.question.content = ''
      this.question.type = ''
      this.question.questionNum = ''
      this.question.id = ''
      this.question.optionContent = ''
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let array = []
          for (let i = 0;i < this.questionForm.optionContents.length;i++){
            array.push(this.questionForm.optionContents[i].content)
          }
          addQuestion(this.questionForm.content,this.questionForm.type,array).then((res) => {
            if (res.data.code == '200'){
              this.$message.success(res.data.message)
              this.queryList()
              this.cleanQuestionFromBuffer()
              this.addDialogFormVisible = false;
            }else {
              this.$message.error(res.data.message)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.cleanQuestionFromBuffer()
    },
    removeOptionContent(item) {
      var index = this.questionForm.optionContents.indexOf(item)
      if (index !== -1) {
        this.questionForm.optionContents.splice(index, 1)
      }
    },
    addOptionContent() {
      this.questionForm.optionContents.push({
        content: '',
        key: Date.now()
      });
    }
  }
}
</script>

<style scoped>
.dw-table-form {
  background-color: white;
  padding: 20px;
  margin-bottom: 20px;
}

.dw-table {
  background: white;
  padding: 20px;
}

.dw-table .dw-table-title {
  padding-bottom: 20px;
  border-bottom: 1px solid #f3f3f3;
}

.dw-table .dw-table-title h3 {
  padding: 0px;
  margin: 0px;
}

.el-form-item {
  margin-bottom: 0px;
}

.dialog-form-item {
  margin-top: 20px;
}

.dw-pagination {
  padding-top: 20px;
  text-align: right;
}

/*html{*/
/*  filter: invert(1) hue-rotate(180deg);*/
/*}*/

</style>
